package com.probox.common.entity.service.platfom.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.PlatformException;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.entity.domain.platfom.PlatformCmsClass;
import com.probox.common.entity.domain.platfom.PlatformInfo;
import com.probox.common.entity.domain.platfom.PlatformTemplate;
import com.probox.common.entity.domain.platfom.vo.NavigateVo;
import com.probox.common.entity.domain.platfom.vo.PlatformInfoVo;
import com.probox.common.entity.domain.product.ProductBrand;
import com.probox.common.entity.domain.product.ProductCategory;
import com.probox.common.entity.domain.product.ProductGroup;
import com.probox.common.entity.domain.system.SysDictData;
import com.probox.common.entity.mapper.platfom.PlatformInfoMapper;
import com.probox.common.entity.service.customer.ILevelPrivilegeService;
import com.probox.common.entity.service.order.IOrderShipAutoService;
import com.probox.common.entity.service.platfom.IPlatformCmsClassService;
import com.probox.common.entity.service.platfom.IPlatformGeneralsettingsService;
import com.probox.common.entity.service.platfom.IPlatformInfoService;
import com.probox.common.entity.service.platfom.IPlatformTemplateService;
import com.probox.common.entity.service.product.IProductBrandService;
import com.probox.common.entity.service.product.IProductCategoryService;
import com.probox.common.entity.service.product.IProductGroupService;
import com.probox.common.entity.service.system.ISysDictDataService;
import com.probox.common.entity.service.system.ISysRoleService;
import com.probox.common.entity.service.system.ISysUserService;
import com.probox.common.entity.service.wechat.WechatMiniService;
import com.probox.customer.api.domain.CreateInfoVo;
import com.probox.order.api.domain.OrderShipAutoVo;
import com.probox.systemApi.domain.SysUser;
import com.probox.wechat.api.domain.WechatAuthorizationInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 平台信息Service业务层处理
 *
 * @date 2021-06-19
 */
@Service
@Transactional
public class PlatformInfoServiceImpl extends ServiceImpl<PlatformInfoMapper, PlatformInfo> implements IPlatformInfoService {
    @Autowired
    private PlatformInfoMapper platformInfoMapper;


    @Autowired
    private IPlatformGeneralsettingsService iPlatformGeneralsettingsService;

    @Autowired
    private IPlatformCmsClassService iPlatformCmsClassService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private ISysUserService iSysUserService;


    @Autowired
    private ILevelPrivilegeService iLevelPrivilegeService;

    @Autowired
    private WechatMiniService wechatMiniService;

    @Autowired
    private IOrderShipAutoService shipAutoService;

    @Autowired
    private IProductBrandService navigateService;

    @Autowired
    private IProductGroupService lunwenCategoryService;

    @Autowired
    private IProductCategoryService majorService;

    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 查询平台信息
     *
     * @return 平台信息
     */
    @Override
    public PlatformInfo selectPlatformInfoById() {
        Long platformId = SecurityUtils.getPlatformId();
        if (ObjectUtil.isEmpty(platformId)) new BaseException("当前用户有问题,请刷新页面");
        return this.getById(platformId);
    }


    /**
     * 获得平台的信息
     *
     * @return
     */
    @Override
    public PlatformInfoVo getInfo() {
        PlatformInfoVo platformInfoVo = new PlatformInfoVo();
        Long customerPlatformUid = SecurityUtils.getCustomerPlatformUid();
        if (ObjectUtil.isEmpty(customerPlatformUid)) throw new PlatformException("该用户所属平台不存在！");
        PlatformInfo platformInfo = this.getById(customerPlatformUid);
        if (ObjectUtil.isNotEmpty(platformInfo)) BeanUtils.copyProperties(platformInfo, platformInfoVo);
        List<ProductBrand> navs = navigateService.bulidSelect();
        List<NavigateVo> navigateVoList = new ArrayList<>();
        for(ProductBrand brand:navs){
            NavigateVo vo = new NavigateVo();
            vo.setTitle(brand.getBrandName());
            vo.setLink(brand.getBrandUrl());
            navigateVoList.add(vo);
        }
        //设置顶部导航栏
        platformInfoVo.setNavigateList(navigateVoList);
        //设置论文分类
        ProductGroup category = new ProductGroup();
        category.setParentGroupUid(0L);
        category.setDataStatus(DataStatus.valid.getKey());
        platformInfoVo.setCategoryList(lunwenCategoryService.queryList(category));
        //设置论文专业
        ProductCategory major = new ProductCategory();
        major.setDataStatus(DataStatus.valid.getKey());
        major.setPlatformUid(1L);
        List<ProductCategory> majorList = majorService.queryList(major);
        platformInfoVo.setMajorList(majorList);
        List<ProductCategory> showMajorList = new ArrayList<>();
        for (ProductCategory c:majorList) {
            if (c.getCategoryPuid()>0L && c.getIsShow().equals("1") && c.getCategoryDepth()==1){
                showMajorList.add(c);
            }
        }
        platformInfoVo.setShowMajorList(showMajorList);

        //热门搜索
        SysDictData dictData = new SysDictData();
        dictData.setStatus("0");
        dictData.setDictType("sys_hot_search");
        List<SysDictData> dictList = dictDataService.selectDictDataList(dictData);
        List<String> hot = new ArrayList<>();
        for (SysDictData dict:dictList) {
            hot.add(dict.getDictLabel());
        }
        platformInfoVo.setHotSearch(hot);

        //微信在线咨询
        dictData = new SysDictData();
        dictData.setStatus("0");
        dictData.setDictType("sys_weixin_zixun");
        dictList = dictDataService.selectDictDataList(dictData);
        List<String> weixin = new ArrayList<>();
        for (SysDictData dict:dictList) {
            weixin.add(dict.getDictIcon());
        }
        platformInfoVo.setWeixinZiXun(weixin);

        //QQ在线咨询
        dictData = new SysDictData();
        dictData.setStatus("0");
        dictData.setDictType("sys_qq_zixun");
        dictList = dictDataService.selectDictDataList(dictData);
        List<String[]> qq = new ArrayList<>();
        for (SysDictData dict:dictList) {
            String[] qqs = {dict.getDictLabel(),dict.getDictValue()};
            qq.add(qqs);
        }
        platformInfoVo.setQqZiXun(qq);

        //左侧广告图
        dictData = new SysDictData();
        dictData.setStatus("0");
        dictData.setDictType("sys_left_ad");
        dictList = dictDataService.selectDictDataList(dictData);
        List<String[]> ad = new ArrayList<>();
        for (SysDictData dict:dictList) {
            String[] ads = {dict.getDictIcon(),dict.getRemark()};
            ad.add(ads);
        }
        platformInfoVo.setLeftAd(ad);

        //网站文案

        platformInfoVo.setDownloadButton("下载");
        platformInfoVo.setMaiduanButton("买断");
        platformInfoVo.setContinueReadTxt("免费内容已读完，展开阅读全文>>");
        platformInfoVo.setServiceTime("服务时间：08：00--22：00若不在服务时间，您可以先进行留言，客服老师上班后会第一时间进行给您回复。");
        platformInfoVo.setDownloadTip("");
        platformInfoVo.setVipLowestTxt("");
        dictData = new SysDictData();
        dictData.setStatus("0");
        dictData.setDictType("sys_word_set");
        dictList = dictDataService.selectDictDataList(dictData);
        for (SysDictData dict:dictList) {
            if(dict.getDictValue().equals("continue_read_txt")){
                platformInfoVo.setContinueReadTxt(dict.getRemark());
            }
            if(dict.getDictValue().equals("maiduan_button")){
                platformInfoVo.setMaiduanButton(dict.getDictLabel());
            }
            if(dict.getDictValue().equals("download_button")){
                platformInfoVo.setDownloadButton(dict.getDictLabel());
            }
            if(dict.getDictValue().equals("service_time")){
                platformInfoVo.setServiceTime(dict.getRemark());
            }
            if(dict.getDictValue().equals("download_tip")){
                platformInfoVo.setDownloadTip(dict.getRemark());
            }
            if(dict.getDictValue().equals("vip_lowest_txt")){
                platformInfoVo.setVipLowestTxt(dict.getRemark());
            }

        }

        return platformInfoVo;
    }

    /**
     * 查询平台信息列表
     *
     * @param platformInfo 平台信息
     * @return 平台信息
     */
    @Override
    public List<PlatformInfo> queryList(PlatformInfo platformInfo) {
        QueryWrapper<PlatformInfo> queryWrapper = Wrappers.query();
        if (ObjectUtil.isNotEmpty(platformInfo.getPlatformName())) {
            queryWrapper.like("PLATFORM_NAME", platformInfo.getPlatformName());
        }
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (ObjectUtil.isEmpty(SecurityUtils.getUserId())) throw new PlatformException("当前账号不存在,请刷新页面！");
        queryWrapper.eq("CREATE_USER", SecurityUtils.getUserId());

        if (ObjectUtil.isNotEmpty(platformInfo.getMainCategory()) && !"all".equals(platformInfo.getMainCategory())) {
            queryWrapper.eq("MAIN_CATEGORY", platformInfo.getMainCategory());
        }

        return platformInfoMapper.selectList(queryWrapper);
    }

    /**
     * 查询所有的店铺信息
     *
     * @param platformInfo
     * @return
     */
    @Override
    public List<PlatformInfo> queryListStore(PlatformInfo platformInfo) {
        QueryWrapper<PlatformInfo> queryWrapper = Wrappers.query();
        if (ObjectUtil.isNotEmpty(platformInfo.getPlatformName())) {
            queryWrapper.like("PLATFORM_NAME", platformInfo.getPlatformName());
        }
        queryWrapper.ne("PLATFORM_UID", 1);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (ObjectUtil.isNotEmpty(platformInfo.getMainCategory()) && !"all".equals(platformInfo.getMainCategory())) {
            queryWrapper.eq("MAIN_CATEGORY", platformInfo.getMainCategory());
        }
        if (ObjectUtil.isNotEmpty(platformInfo.getAuthTime())) {
            Date authTime = platformInfo.getAuthTime();
            queryWrapper.le("AUTH_TIME", DateUtils.addDay(authTime, 30));
            queryWrapper.gt("AUTH_TIME", authTime);
        }
        if (ObjectUtil.isNotEmpty(platformInfo.getIsAuth())) {
            queryWrapper.eq("IS_AUTH", platformInfo.getIsAuth());
        }
        queryWrapper.orderByDesc("CREATE_TIME");
        return platformInfoMapper.selectList(queryWrapper);
    }

    /**
     * 新增平台信息
     *
     * @param platformInfo 平台信息
     * @return 结果
     */
    @Override
    public Long insertPlatformInfo(PlatformInfo platformInfo) {
        Long userId = SecurityUtils.getUserId();
        if (ObjectUtil.isEmpty(userId)) throw new BaseException("请重新刷新页面！");
        // 先查询是否有失效的平台,有失效的平台则不让他添加店铺
        checkAuth(userId);
        SysUser user = iSysRoleService.getUserAndSetRole(userId);
        if(ObjectUtil.isEmpty(user)) throw new BaseException("用户不存在！");
        platformInfo.setServePhone(user.getPhonenumber());
        platformInfo.setContactPerson(user.getUserName());
        platformInfo.setPlatformPhone(user.getPhonenumber());
        platformInfo.setCreateUser(userId);
        platformInfo.setCreateTime(DateUtil.date());
        platformInfo.setDataStatus(DataStatus.valid.getKey());
        platformInfo.setAuthTime(DateUtils.addDay(DateUtil.date(), 7));
        boolean save = this.save(platformInfo);
        if (save) {
            boolean b = iPlatformGeneralsettingsService.insertPlatformGeneralsettings(platformInfo.getPlatformUid());//添加店铺配置
            if (!b) throw new BaseException("添加失败,请联系管理员！");
            // 添加自动收货配置
            OrderShipAutoVo vo = new OrderShipAutoVo();
            vo.setPlatformUid(platformInfo.getPlatformUid());
            vo.setAutoDate(7L);
            vo.setDelayedDate(5L);
            vo.setUpdateUser(SecurityUtils.getUserId());
            vo.setUpdateName(SecurityUtils.getUsername());
            vo.setUpdateTime(DateUtil.date());

            boolean booleanR = shipAutoService.addShipAuto(vo);
            if (booleanR == false) throw new BaseException("添加失败,请联系管理员！");
            //新增店铺资讯分类
            iPlatformCmsClassService.insertPlatformCmsClass(new PlatformCmsClass(0L, platformInfo.getPlatformUid()));
            iPlatformCmsClassService.insertPlatformCmsClass(new PlatformCmsClass(1L, platformInfo.getPlatformUid()));
            iPlatformCmsClassService.insertPlatformCmsClass(new PlatformCmsClass(2L, platformInfo.getPlatformUid()));
            // 新增店铺销售渠道
            WechatAuthorizationInfoVo wechatAuthorizationInfoVo = new WechatAuthorizationInfoVo();
            wechatAuthorizationInfoVo.setPlatformId(String.valueOf(platformInfo.getPlatformUid()));
            wechatAuthorizationInfoVo.setAuthorizerType("H5");
            wechatMiniService.saveAuthorizationInfo(wechatAuthorizationInfoVo);
            // 创建店铺默认权益信息
            CreateInfoVo createInfoVo = new CreateInfoVo();
            createInfoVo.setPlatform(platformInfo.getPlatformUid());
            createInfoVo.setUserId(SecurityUtils.getUserId());
            createInfoVo.setUserName(SecurityUtils.getUsername());
            iLevelPrivilegeService.saveDefaultPrivilegeAndDefinition(createInfoVo);
            return platformInfo.getPlatformUid();
        } else {
            throw new BaseException("添加失败,请联系管理员！");
        }

    }

    /**
     * 修改平台信息
     *
     * @param platformInfo 平台信息
     * @return 结果
     */
    @Override
    public boolean updatePlatformInfo(PlatformInfo platformInfo) {
        platformInfo.setUpdateUser(SecurityUtils.getUserId());
        platformInfo.setUpdateTime(DateUtil.date());
        return this.updateById(platformInfo);
    }

    @Override
    public boolean updatePlatformInfoTime(PlatformInfo platformInfo) {
        if (DateUtil.date().compareTo(platformInfo.getAuthTime()) > 0) {
            platformInfo.setIsAuth(DataStatus.delete.getKey());
        }
        platformInfo.setUpdateUser(SecurityUtils.getUserId());
        platformInfo.setUpdateTime(DateUtil.date());
        return this.updateById(platformInfo);
    }


    /**
     * 删除平台信息
     *
     * @param map
     * @return 结果
     */
    @Override
    public boolean deletePlatformInfoByIds(HashMap map) {
        SysUser sysUser = iSysUserService.selectUserById(SecurityUtils.getUserId());
        if (ObjectUtil.isEmpty(sysUser)) throw new BaseException("用户不存在！");
        if (!SecurityUtils.matchesPassword(Convert.toStr(map.get("pa")), sysUser.getPassword()))
            throw new BaseException("密码错误！");
        UpdateWrapper<PlatformInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PLATFORM_UID", map.get("platformUid"));
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_USER", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        return this.update(updateWrapper);
    }

    /**
     * 校验是否让用户创建店铺
     *
     * @param userId
     * @return
     */
    @Override
    public boolean checkAuth(Long userId) {
        // 先查询是否有失效的平台,有失效的平台则不让他添加店铺
        QueryWrapper<PlatformInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CREATE_USER", userId);
        List<PlatformInfo> platformInfos = platformInfoMapper.selectList(queryWrapper);
        Integer count = platformInfos.size();
        if (count > 0) {
            //
            AtomicReference<Integer> vaild = new AtomicReference<>(0);
            platformInfos.forEach(info -> {
                if (DataStatus.invalid.getKey().equals(info.getIsAuth())) {
                    vaild.set(1);
                }
            });
            if (vaild.get() > 0) throw new PlatformException("您的其他店铺必须为正式才能创建！");
        }
        return true;
    }

}
